// ListManager.cpp: implementation of the CListManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Lister.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CLister::CLister(int iCount)
{
	LPLISTNODE pListNode = NULL;
	m_FreeList = NULL;
	m_ValueList = NULL;
	::InitializeCriticalSection(&m_csLock);
//	InitializeCriticalSectionAndSpinCount(&m_csLock,4000);
	for(int i=0;i<iCount;++i)
	{
		pListNode = (LPLISTNODE) malloc(sizeof(LISTNODE));
		if(pListNode != NULL)
		{
			pListNode->pNext = m_FreeList;
			m_FreeList = pListNode;
		}
	}
}

CLister::~CLister()
{
	EnterCriticalSection(&m_csLock);
	LPLISTNODE pListNode = NULL;
	while(m_FreeList != NULL)
	{
		pListNode = m_FreeList;
		m_FreeList = m_FreeList->pNext;
		free(pListNode);
	}
	while(m_ValueList != NULL)
	{
		pListNode = m_ValueList;
		m_ValueList = m_ValueList->pNext;
		free(pListNode);
	}
	m_FreeList = NULL;
	m_ValueList = NULL;
	DeleteCriticalSection(&m_csLock);
}

void CLister::Push(void *pValue)
{
	EnterCriticalSection(&m_csLock);
	LPLISTNODE pListNode = m_FreeList;
	if(pListNode == NULL)
	{
		pListNode = (LPLISTNODE) malloc(sizeof(LISTNODE));
	}
	else
	{
		m_FreeList = m_FreeList->pNext;
	}
	if(pListNode != NULL)
	{
		pListNode->pValue = pValue;
		pListNode->pNext = m_ValueList;
		m_ValueList = pListNode;
	}
	LeaveCriticalSection(&m_csLock);
}

void *CLister::Pop()
{
	void *pRet = NULL;
	EnterCriticalSection(&m_csLock);
	LPLISTNODE pListNode = m_ValueList;
	if(pListNode != NULL)
	{
		m_ValueList = m_ValueList->pNext;
		pRet = pListNode->pValue;
		pListNode->pNext = m_FreeList;
		m_FreeList = pListNode;
	}
	LeaveCriticalSection(&m_csLock);
	return pRet;
}